const api = require('../../../utils/api')
const config = require('../../../utils/config')
const app = require('../../../utils/app')

Page({
  data: {
    orderId: null,
    orderInfo: null,
    loading: true,
    paymentOptions: [
      { id: 'wxpay', name: '微信支付', icon: '/static/images/icons/wechat-pay.png', checked: true },
      { id: 'alipay', name: '支付宝', icon: '/static/images/icons/alipay.png', checked: false },
      { id: 'balance', name: '余额支付', icon: '/static/images/icons/balance-pay.png', checked: false }
    ],
    selectedPayment: 'wxpay',
    countdown: {
      minutes: 15,
      seconds: 0
    },
    timer: null,
    paying: false
  },

  onLoad(options) {
    const { id } = options;
    
    if (!id) {
      wx.showToast({
        title: '订单ID不能为空',
        icon: 'none'
      });
      
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      
      return;
    }
    
    this.setData({ orderId: id });
    this.loadOrderDetail();
    this.startCountdown();
  },
  
  onUnload() {
    // 清理定时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },
  
  // 加载订单详情
  loadOrderDetail() {
    this.setData({ loading: true });
    
    console.log('[支付页] 加载订单详情，订单ID:', this.data.orderId);
    // 订单详情API需要手动拼接ID
    const url = config.API.ORDER.DETAIL + this.data.orderId;
    
    api.get(url)
      .then(res => {
        console.log('[支付页] 获取订单详情响应:', res);
        
        if (res.code === 200 || res.code === 201 || res.code === 0) {
          console.log('[支付页] 获取订单详情成功');
          this.setData({
            orderInfo: res.data,
            loading: false
          });
          
          // 如果订单状态不是待支付，提示用户
          if (res.data && res.data.status !== 0) {
            wx.showModal({
              title: '提示',
              content: '该订单不是待支付状态，无需支付',
              showCancel: false,
              success: () => {
                wx.redirectTo({
                  url: `/pages/order/detail/index?id=${this.data.orderId}`
                });
              }
            });
          }
        } else {
          console.error('[支付页] 获取订单失败:', res);
          wx.showToast({
            title: res.message || '获取订单失败',
            icon: 'none'
          });
          
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      })
      .catch(err => {
        console.error('[支付页] 获取订单详情失败:', err);
        
        // 记录更详细的错误信息
        if (err.statusCode) {
          console.error('[支付页] HTTP状态码:', err.statusCode);
        }
        if (err.data) {
          console.error('[支付页] 错误响应数据:', err.data);
        }
        
        wx.showToast({
          title: '获取订单失败，请重试',
          icon: 'none'
        });
        
        this.setData({ loading: false });
        
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      });
  },
  
  // 选择支付方式
  selectPayment(e) {
    const paymentId = e.currentTarget.dataset.id;
    
    // 更新选中状态
    const paymentOptions = this.data.paymentOptions.map(item => {
      return {
        ...item,
        checked: item.id === paymentId
      };
    });
    
    this.setData({
      paymentOptions,
      selectedPayment: paymentId
    });
  },
  
  // 开始倒计时
  startCountdown() {
    // 清理可能存在的定时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
    
    // 设置初始倒计时时间 (15分钟)
    this.setData({
      countdown: {
        minutes: 15,
        seconds: 0
      }
    });
    
    // 创建定时器
    const timer = setInterval(() => {
      let { minutes, seconds } = this.data.countdown;
      
      // 计算新的倒计时
      if (seconds > 0) {
        seconds -= 1;
      } else if (minutes > 0) {
        minutes -= 1;
        seconds = 59;
      } else {
        // 倒计时结束
        clearInterval(timer);
        
        wx.showModal({
          title: '提示',
          content: '支付超时，订单已自动取消',
          showCancel: false,
          success: () => {
            wx.navigateBack();
          }
        });
        
        return;
      }
      
      // 更新倒计时
      this.setData({
        countdown: { minutes, seconds },
        timer
      });
    }, 1000);
  },
  
  // 支付方法
  pay() {
    if (this.data.paying) {
      return;
    }
    
    this.setData({ paying: true });
    
    wx.showLoading({
      title: '处理中...',
      mask: true
    });
    
    console.log('[支付页] 请求支付参数，订单ID:', this.data.orderId);
    
    // 调用支付API
    const url = config.API.ORDER.PAY.replace(':id', this.data.orderId);
    
    api.post(url)
      .then(res => {
        wx.hideLoading();
        console.log('[支付页] 获取支付参数响应:', res);
        
        if (res.code === 200 || res.code === 0) {
          // 获取支付参数成功
          const payParams = res.data;
          console.log('[支付页] 获取支付参数成功:', payParams);
          
          // 调用微信支付
          this.callWxPayment(payParams);
        } else {
          console.error('[支付页] 获取支付参数失败:', res);
          wx.showToast({
            title: res.message || '获取支付参数失败',
            icon: 'none'
          });
          this.setData({ paying: false });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('[支付页] 请求支付参数失败:', err);
        wx.showToast({
          title: '网络请求失败，请重试',
          icon: 'none'
        });
        this.setData({ paying: false });
      });
  },
  
  // 调起微信支付
  callWxPayment(payParams) {
    console.log('[支付页] 调起微信支付');
    
    wx.requestPayment({
      ...payParams,
      success: (res) => {
        console.log('[支付页] 支付成功:', res);
        wx.showToast({
          title: '支付成功',
          icon: 'success'
        });
        
        // 更新全局订单列表状态
        const eventChannel = this.getOpenerEventChannel();
        if (eventChannel && eventChannel.emit) {
          eventChannel.emit('orderStatusUpdated', { orderId: this.data.orderId });
        }
        
        // 延迟一下，显示支付成功提示后再跳转
        setTimeout(() => {
          // 跳转到订单详情页，并传递刷新标志
          wx.redirectTo({
            url: `/pages/order/detail/index?id=${this.data.orderId}&refresh=1`
          });
        }, 1500);
      },
      fail: (err) => {
        console.error('[支付页] 支付失败或取消:', err);
        if (err.errMsg === 'requestPayment:fail cancel') {
          wx.showToast({
            title: '支付已取消',
            icon: 'none'
          });
        } else {
          wx.showToast({
            title: '支付失败: ' + err.errMsg,
            icon: 'none'
          });
        }
      },
      complete: () => {
        this.setData({ paying: false });
      }
    });
  },
  
  // 取消订单
  cancelOrder() {
    wx.showModal({
      title: '提示',
      content: '确定要取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '取消中...',
            mask: true
          });
          
          const url = config.API.ORDER.CANCEL.replace(':id', this.data.orderId);
          
          api.put(url)
            .then(res => {
              wx.hideLoading();
              
              if (res.code === 200) {
                wx.showToast({
                  title: '订单已取消',
                  icon: 'success'
                });
                
                setTimeout(() => {
                  wx.navigateBack();
                }, 1500);
              } else {
                wx.showToast({
                  title: res.message || '取消订单失败',
                  icon: 'none'
                });
              }
            })
            .catch(err => {
              wx.hideLoading();
              console.error('取消订单失败:', err);
              wx.showToast({
                title: '取消订单失败，请重试',
                icon: 'none'
              });
            });
        }
      }
    });
  },
  
  // 返回订单列表
  goToOrderList() {
    wx.redirectTo({
      url: '/pages/order/index'
    });
  }
}) 